package com.ucode.crm.service.impl;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ucode.crm.dictionary.CrmResultDefineMsg;
import com.ucode.crm.dictionary.ModuleType;
import com.ucode.crm.dictionary.TeamUserPower;
import com.ucode.crm.mapper.BusinessMapper;
import com.ucode.crm.mapper.CrmTeamUserMapper;
import com.ucode.crm.mapper.CustomerMapper;
import com.ucode.crm.mapper.OwnerChangeRecordMapper;
import com.ucode.crm.mode.Business;
import com.ucode.crm.mode.CrmTeamUser;
import com.ucode.crm.mode.Customer;
import com.ucode.crm.mode.OwnerChangeRecord;
import com.ucode.crm.service.BusinessService;
import com.ucode.crm.vo.BusinessVo;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import com.ucode.tool.util.IdentifyUtils;

@Service
public class BusinessServiceImpl implements BusinessService {

    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private CrmTeamUserMapper crmTeamUserMapper;
    @Autowired
    private OwnerChangeRecordMapper ownerChangeRecordMapper;
    
    @Override
    @Transactional(rollbackFor=Exception.class)
    public Business insert(Business business) {
        
        Date now = new Date();
        business.setId(IdentifyUtils.getDefaultSnowflakeId());
        business.setCreatedTime(now);
        business.setUpdatedTime(now);
        
        if(businessMapper.insert(business) == 0){
            throw new UcodeServiceException(ResultCodeEnum.FAILED);
        }
        
        CrmTeamUser crmTeamUser = new CrmTeamUser(business.getId(), ModuleType.business.code, business.getOwnerUserId(), TeamUserPower.owner.code);
        crmTeamUser.setId(IdentifyUtils.getDefaultSnowflakeId());
        crmTeamUser.setCreatedTime(now);
        crmTeamUser.setUpdatedTime(now);
        crmTeamUserMapper.save(crmTeamUser);
        
        incrBusinessCount(business.getCustomerId(), 1);
        return business;
    }
    
    private void incrBusinessCount(Long customerId,int delta){
        Customer customer = customerMapper.findById(customerId);
        if(customer != null){
            int i = customerMapper.incrBusinessCount(customer.getId(), delta, customer.getBusinessCount());
            if(i == 0){
                incrBusinessCount(customerId, delta);
            }
        }
    }

    @Override
    public int update(Business business) {
        return businessMapper.update(business);
    }

    @Override
    public int deleteByLogic(Long id) {
        return businessMapper.deleteByLogic(id);
    }

    @Override
    public int delete(List<Long> ids) {
        return businessMapper.delete(ids);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int transfer(Long id, Long ownerUserId, Long operatorId) {
        Business business = businessMapper.findById(id);
        
        if(business == null || business.getDeltag() == 1)
            throw new UcodeServiceException(ResultCodeEnum.NO_RECORD);
        
        //自己转让给自己
        if(business.getOwnerUserId().equals(ownerUserId))
            throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.business_transfer_itself_error,business.getName());
        
        Date now = new Date();
        //负责人变更记录
        OwnerChangeRecord ownerChangeRecord = new OwnerChangeRecord(business.getId(), ModuleType.business.code, business.getOwnerUserId(), ownerUserId, operatorId);
        ownerChangeRecord.setId(IdentifyUtils.getDefaultSnowflakeId());
        ownerChangeRecord.setCreatedTime(now);
        ownerChangeRecord.setUpdatedTime(now);
        ownerChangeRecordMapper.insert(ownerChangeRecord);
        
        //跟进团队
        CrmTeamUser crmTeamUser = new CrmTeamUser(business.getId(), ModuleType.business.code, ownerUserId, TeamUserPower.owner.code);
        crmTeamUser.setId(IdentifyUtils.getDefaultSnowflakeId());
        crmTeamUser.setCreatedTime(now);
        crmTeamUser.setUpdatedTime(now);
        crmTeamUserMapper.save(crmTeamUser);
        
        CrmTeamUser oldOwneUser = crmTeamUserMapper.find(business.getId(), ModuleType.business.code, business.getOwnerUserId());
        //移除原负责人
        if(oldOwneUser != null){
            crmTeamUserMapper.delete(oldOwneUser.getId());
        }
        
        if(businessMapper.transfer(id, ownerUserId,business.getOwnerUserId()) == 0){
            throw new UcodeServiceException(ResultCodeEnum.FAILED.code,CrmResultDefineMsg.business_transfer_permission_error,business.getName());
        }
        
        return 1;
    }
    
    @Override
    public int updateCustomerOwnerUser(Long customerId, Long ownerUserId) {
        return businessMapper.updateCustomerOwnerUser(customerId, ownerUserId);
    }

    @Override
    public Business findById(Long id) {
        return businessMapper.findById(id);
    }

    @Override
    public List<Business> findByIds(List<Long> ids) {
        return businessMapper.findByIds(ids);
    }
    
    @Override
    public BusinessVo findVoById(Long id) {
        return businessMapper.findVoById(id);
    }

    @Override
    public List<BusinessVo> findVoByIds(List<Long> ids) {
        return businessMapper.findVoByIds(ids);
    }

    @Override
    public Paginator<BusinessVo> queryPageByCustomer(Long customerId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<BusinessVo> list = businessMapper.queryListByCustomerId(customerId);
        PageInfo<BusinessVo> pageInfo = new PageInfo<>(list);
        return new Paginator<>(pageInfo.getTotal(), pageInfo.getPageNum(), pageInfo.getPageSize(), list);
    }

}
